import tensorflow as tf
import numpy as np
# 本节重点 损失函数

BATCH_SIZE = 8
seed = 23455
# tf_upgrade_v2 --infile v1.tf3_3.py --outfile v2.0.py

# 基于seed产生随机数
rng = np.random.RandomState(seed)
# 随机数返回32x2矩阵，表示32组数据
X = rng.rand(32,2)
# 构建Y标签，规定和为1为阈值，小于认为合格
Y = [[x1+x2+(rng.rand()/10.0-0.05)] for (x1,x2) in X] # 函数生成[0,1)区间数
print ("X:\n",X)
print ("Y:\n",Y)

# x = tf.constant([[0.7, 0.5]])
x = tf.placeholder(tf.float32,shape=(None,2))
y_ = tf.placeholder(tf.float32,shape=(None,1)) # 输出标签

w1 = tf.Variable( tf.random_normal([2,1], stddev=1, seed=1) )
# w2 = tf.Variable( tf.random_normal([3,1], stddev=1, seed=1) )

# Forward Propagation
# a = tf.matmul(x,w1) # 1st layer
y = tf.matmul(x,w1) # output

# 损失函数，反向传播
# loss_mse = tf.reduce_mean(tf.square(y_-y))

COST = 1
PROFIT =9
loss = tf.reduce_sum(tf.where(tf.greater(y,y_),(y-y_)*COST,(y_-y)*PROFIT))


train_step = tf.train.GradientDescentOptimizer(0.001).minimize(loss)
# train_step = tf.train.MomentOptimizer(0.001).minimize(loss)
# train_step = tf.train.AdamDescentOptimizer(0.001).minimize(loss)

with tf.Session() as sess:
    init_op = tf.global_variables_initializer() # 全局初始化参数，初始化节点
    sess.run(init_op)
    # print ( "y in tf3_3.py is : \n",sess.run(y) )
    # print ( "y in tf3_3.py is : \n",sess.run(y,feed_dict={x:[[0.7,0.5]]}) )
    
    # 打印出优化前参数
    print("w1:\n",sess.run(w1))
    # print("w2:\n",sess.run(w2))
    print("\n")

    STEPS = 20000
    for i in range(STEPS):
        start = (i*BATCH_SIZE)%32
        # end = start+BATCH_SIZE
        end = (i*BATCH_SIZE) %32 +BATCH_SIZE
        sess.run(train_step,feed_dict={x: X[start:end], y_:Y[start:end]})
        if i%500 ==0:
            # total_loss = sess.run(loss,feed_dict = {x:X, y_:Y})
            print("训练 %d 步后，损失" % (i))
            print(sess.run(w1),"\n")
    # 训练后参数
    print("\n")
    print("Final w:\n",sess.run(w1))